﻿/* Copyright 2007-2009 dnAnalytics Project.
 *
 * Contributors to this file:
 * Jurgen Van Gael
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 *   list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the dnAnalytics Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
using System;
using dnAnalytics.Random;

namespace dnAnalytics.Mcmc
{
    /// <summary>
    /// A method which samples datapoints from a proposal distribution. The implementation of this sampler
    /// is stateless: no variables are saved between two calls to Sample. This proposal is different from
    /// <seealso cref="LocalProposalSampler{T}"/> in that it doesn't take any parameters; it samples random
    /// variables from the whole domain.
    /// </summary>
    /// <typeparam name="T">The type of the datapoints.</typeparam>
    /// <returns>A sample from the proposal distribution.</returns>
    public delegate T GlobalProposalSampler<T>();

    /// <summary>
    /// A method which samples datapoints from a proposal distribution given an initial sample. The implementation 
    /// of this sampler is stateless: no variables are saved between two calls to Sample. This proposal is different from
    /// <seealso cref="GlobalProposalSampler{T}"/> in that it samples locally around an initial point. In other words, it
    /// makes a small local move rather than producing a global sample from the proposal.
    /// </summary>
    /// <typeparam name="T">The type of the datapoints.</typeparam>
    /// <param name="init">The initial sample.</param>
    /// <returns>A sample from the proposal distribution.</returns>
    public delegate T LocalProposalSampler<T>(T init);

    /// <summary>
    /// A function which evaluates a density.
    /// </summary>
    /// <typeparam name="T">The type of data the distribution is over.</typeparam>
    /// <param name="sample">The sample we want to evaluate the density for.</param>
    public delegate double Density<T>(T sample);

    /// <summary>
    /// A function which evaluates a log density.
    /// </summary>
    /// <typeparam name="T">The type of data the distribution is over.</typeparam>
    /// <param name="sample">The sample we want to evaluate the log density for.</param>
    public delegate double DensityLn<T>(T sample);

    /// <summary>
    /// A function which evaluates the log of a transition kernel probability.
    /// </summary>
    /// <typeparam name="T">The type for the space over which this transition kernel is defined.</typeparam>
    /// <param name="to">The new state in the transition.</param>
    /// <param name="from">The previous state in the transition.</param>
    /// <returns>The log probability of the transition.</returns>
    public delegate double TransitionKernelLn<T>(T to, T from);

    /// <summary>
    /// The interface which every sampler must implement.
    /// </summary>
    /// <typeparam name="T">The type of samples this sampler produces.</typeparam>
    public abstract class McmcSampler<T>
    {
        /// <summary>
        /// The random number generator for this class.
        /// </summary>
        private System.Random mRandomNumberGenerator;

        /// <summary>
        /// Keeps track of the number of accepted samples.
        /// </summary>
        protected int mAccepts;

        /// <summary>
        /// Keeps track of the number of calls to the proposal sampler.
        /// </summary>
        protected int mSamples;

        /// <summary>
        /// Initializes a new instance of the <see cref="AbstractRandomNumberGenerator"/> class.
        /// </summary>
        /// <remarks>Thread safe instances are two and half times slower than non-thread
        /// safe classes.</remarks>
        protected McmcSampler()
        {
            mAccepts = 0;
            mSamples = 0;
            RandomNumberGenerator = new System.Random();
        }

        /// <summary>
        /// Gets or sets the random number generator.
        /// </summary>
        /// <exception cref="ArgumentNullException">When the random number generator is null.</exception>
        public System.Random RandomNumberGenerator
        {
            get { return mRandomNumberGenerator; }

            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException(Properties.Resources.RandomNumberGeneratorCannotBeNull);
                }
                mRandomNumberGenerator = value;
            }
        }

        /// <summary>
        /// Returns one sample.
        /// </summary>
        public abstract T Sample();

        /// <summary>
        /// Returns a number of samples.
        /// </summary>
        /// <param name="n">The number of samples we want.</param>
        /// <returns>An array of samples.</returns>
        public virtual T[] Sample(int n)
        {
            T[] ret = new T[n];

            for (int i = 0; i < n; i++)
            {
                ret[i] = Sample();
            }

            return ret;
        }

        /// <summary>
        /// Gets the acceptance rate of the sampler.
        /// </summary>
        public double AcceptanceRate
        {
            get { return (double)mAccepts / (double)mSamples; }
        }
    }
}